import java.util.ArrayList;
import java.util.List;

public class LeetCode {
    int[] ret;
    int[] index;//记录下标
    int[] tmpIndex;
    int[] tmpRet;
    public List<Integer> countSmaller(int[] nums) {
        int n = nums.length;
        ret = new int[n];
        index = new int[n];
        tmpIndex = new int[n];
        tmpRet  = new int[n];
        for (int i = 0; i < n; i++) {
            index[i] = i;
        }
        mergeSort(nums,0,nums.length-1);
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < ret.length; i++) {
            list.add(ret[i]);
        }
        return list;
    }
    public void mergeSort(int[] nums,int left,int right){
        if(left>=right){
            return;
        }
        int mid = (right+left)/2;

        mergeSort(nums,left,mid);
        mergeSort(nums,mid+1,right);

        int cur1 = left,cur2 = mid+1,i = 0;
        while(cur1<=mid && cur2<=right){
            if(nums[cur1]<=nums[cur2]){
                tmpRet[i] = nums[cur2];
                tmpIndex[i++] = index[cur2++];
            }else{
                ret[index[cur1]] += right-cur2+1;
                tmpRet[i] = nums[cur1];
                tmpIndex[i++] = index[cur1++];
            }
        }
        while(cur1<=mid){
            tmpRet[i] = nums[cur2];
            tmpIndex[i++] = index[cur2++];
        }
        while(cur2<=right){
            tmpRet[i] = nums[cur1];
            tmpIndex[i++] = index[cur1++];
        }
        for (int j = left; j <= right; j++) {
                nums[j] = tmpRet[j-left];
                index[j]  = tmpIndex[j-left];
        }
    }

}
